package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hbase.thirdparty.io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Resource
    private WmMaterialMapper wmMaterialMapper;
    @Resource
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Resource
    private WmNewsTaskService wmNewsTaskService;

    @Resource
    private WmNewsMapper wmNewsMapper;
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID); // 如果请求参数为空，返回参数无效的错误结果
        }
        dto.checkParam(); // 检查请求参数的有效性

        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>(); // 创建LambdaQueryWrapper对象用于构建查询条件
        WmUser user = WmThreadLocalUtil.getUser(); // 获取当前用户
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN); // 如果用户未登录，返回需要登录的错误结果
        }
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus()); // 添加状态的查询条件
        }

        wrapper.eq(WmNews::getUserId, user.getId()); // 添加用户ID的查询条件
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize()); // 创建分页对象

        if (!StringUtil.isNullOrEmpty(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword()); // 添加标题模糊查询条件
        }
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId()); // 添加频道ID的查询条件
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate()); // 添加发布时间范围查询条件
        }
        wrapper.orderByDesc(WmNews::getCreatedTime); // 按创建时间降序排序
        page = page(page, wrapper); // 执行查询

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal()); // 创建分页响应结果对象
        responseResult.setData(page.getRecords()); // 设置响应结果的数据为查询结果列表


        return responseResult; // 返回响应结果
    }


    /**
     * 发布修改文章或保存为草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        if (Objects.isNull(dto) || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = createWmNewsFromDto(dto); // 创建WmNews对象并从Dto中复制属性

        saveOrUpdateWmNews(wmNews); // 保存或更新新闻对象到数据库


        if (WmNews.Status.NORMAL.getCode() == dto.getStatus()) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS); // 如果新闻状态为草稿，则返回成功结果
        }

        List<String> materials = extractUrlInfo(dto.getContent()); // 提取内容中的图片URL信息
        saveRelativeInfoForContent(materials, wmNews.getId()); // 保存内容图片与素材的关系
        saveRelativeInfoForCover(dto, wmNews, materials); // 保存封面图片与素材的关系

        wmNews = wmNewsMapper.selectById(wmNews.getId());
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl===》文章不存在");
        }

        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {

        if (dto == null || dto.getId() == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        WmNews wmNews = getById(dto.getId());

        if (wmNews == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");

        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态");

        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));
        HashMap<String, Object> map = new HashMap<>();
        map.put("articleId", wmNews.getArticleId());
        map.put("enable", wmNews.getEnable());
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findNews(AdNewsAuthDto dto) {


        Page<WmNews> wmNewsPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        if (dto.getStatus() != null) {
            System.out.println("=======1:" + dto.getStatus());
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (!StringUtils.isBlank(dto.getTitle())) {
            wrapper.eq(WmNews::getTitle, dto.getTitle());
        }
        wmNewsPage = page(wmNewsPage, wrapper);

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) wmNewsPage.getTotal());
        result.setData(wmNewsPage.getRecords());
        return result;
    }

    @Override
    public ResponseResult WmNewsDetails(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult auth_fail(AdNewsAuthDto dto) {

        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaUpdateWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getStatus, 2);
        if (!StringUtils.isBlank(dto.getMsg())) {
            wrapper.set(WmNews::getReason, dto.getMsg());
        }

        boolean isUpdate = update(wrapper);
        if (!isUpdate) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult auth_pass(AdNewsAuthDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaUpdateWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getStatus, 4);
        if (!StringUtils.isBlank(dto.getMsg())) {
            wrapper.set(WmNews::getReason, dto.getMsg());
        }

        boolean isUpdate = update(wrapper);
        if (!isUpdate) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private WmNews createWmNewsFromDto(WmNewsDto dto) {
        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(dto, wmNews); // 将dto对象的属性拷贝到wmNews对象中


        if (CollectionUtils.isNotEmpty(dto.getImages())) {
            String images = String.join(",", dto.getImages()); // 将图片URL列表拼接成字符串
            wmNews.setImages(images); // 设置新闻对象的图片属性
        }

        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null); // 如果新闻类型为自动，则将类型设置为null
        }

        return wmNews;
    }

    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages(); // 获取DTO中的封面图片列表

        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) { // 判断封面类型是否为自动
            if (materials.size() >= 3) { // 如果素材数量大于等于3
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE); // 设置新闻类型为多图
                images = materials.subList(0, 3); // 从素材列表中获取前3个作为封面图片列表
            } else if (materials.size() >= 1 && materials.size() < 3) { // 如果素材数量大于等于1且小于3
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE); // 设置新闻类型为单图
                images = materials.subList(0, 1); // 从素材列表中获取第一个作为封面图片列表
            } else { // 小于1
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE); // 设置新闻类型为无图
            }
        }

        if (CollectionUtils.isNotEmpty(images)) { // 如果封面图片列表不为空
            String strImages = String.join(",", images); // 将封面图片列表转换为逗号分隔的字符串
            wmNews.setImages(strImages); // 设置新闻的封面图片
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE); // 保存封面图片与素材的关系
        }
        updateById(wmNews); // 更新新闻对象到数据库
    }


    private void saveRelativeInfoForContent(List<String> materials, Integer id) {
        saveRelativeInfo(materials, id, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    private void saveRelativeInfo(List<String> materials, Integer id, Short reference) {
        if (CollectionUtils.isEmpty(materials)) {
            return; // 如果素材列表为空，直接返回
        }
        //根据图片url查询素材对象
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
        if (wmMaterials.size() != materials.size()) {
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL); // 如果查询到的素材对象数量与原始素材数量的url不一致，抛出自定义异常
        }

        List<Integer> materialsId = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList()); // 提取素材ID列表
        wmNewsMaterialMapper.saveRelations(materialsId, id, reference); // 保存素材与新闻的关系
    }


    private List<String> extractUrlInfo(String content) {
        List<String> materials = new ArrayList<>(); // 创建存储URL的列表

        List<Map> maps = JSON.parseArray(content, Map.class); // 将JSON字符串解析为List<Map>对象
        for (Map map : maps) { // 遍历每个Map对象
            if ("image".equals(map.get("type"))) { // 判断type是否为"image"
                materials.add((String) map.get("value")); // 将value添加到URL列表中
            }
        }

        return materials; // 返回URL列表
    }


    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId()); // 设置新闻的用户ID为当前用户ID
        wmNews.setCreatedTime(new Date()); // 设置新闻的创建时间为当前时间
        wmNews.setEnable((short) 1); // 设置新闻的启用状态为1（上架）
        wmNews.setSubmitedTime(new Date()); // 设置新闻的发布时间为当前时间

        if (wmNews.getId() == null) { // 如果新闻ID为空，表示是新增新闻
            save(wmNews); // 调用保存方法将新闻对象插入数据库
        } else { // 否则，表示是更新已有新闻
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId())); // 删除新闻与素材的关联关系
            updateById(wmNews); // 调用更新方法更新新闻对象到数据库
        }
    }


}
